package com.txc.cloud.admin.common.config;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.io.FileNotFoundException;
import java.util.Objects;

/**
 * @ClassName: BeanRegister
 * @Author: TXC
 * @Date: 2023-08-18 12:12
 **/
@Component
public class BeanRegister {
    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() throws FileNotFoundException {
        try {
            PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
            YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
            // 自定义yaml文件的存储路径
            yaml.setResources(new ClassPathResource("/permission.yml"));
            configurer.setProperties(Objects.requireNonNull(yaml.getObject()));
            return configurer;
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException) {
                throw (FileNotFoundException) e.getCause();
            }
            throw e;
        }
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
